import 'package:flutter/material.dart';
import 'package:lib_core/lib_core.dart';
import 'package:lib_ui/gen/assets.gen.dart';
import 'package:lib_ui/lib_ui.dart';

import '../../utils/ld_font.dart';
import '../ld_text_field.dart';
import '../main_button.dart';

class InputSheet extends StatelessWidget {
  InputSheet({
    Key? key,
    this.title,
    this.hint,
    this.content,
    this.maxLength,
    this.onConfirm,
  }) : super(key: key);

  String? title;
  String? hint;
  String? content;
  int? maxLength;
  ValueChanged<String>? onConfirm;

  late final RxString _text = (content ?? '').obs;

  late final _isValid = _checkValid(content).obs;

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: const BorderRadius.only(
        topLeft: Radius.circular(21),
        topRight: Radius.circular(21),
      ),
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                if (title != null)
                  Text(
                    title!,
                    style: LDFont.medium(fontSize: 17, color: ColorName.textPrimary),
                  ),
                GestureDetector(
                  onTap: BoostNavigator.instance.pop,
                  child: UIAssets.images.icClose.svg(width: 30, height: 30),
                ),
              ],
            ),
            Container(
              margin: const EdgeInsets.only(top: 16),
              child: LDTextField(
                hint: hint,
                text: content,
                type: LDTextFieldType.overLimit,
                maxLength: maxLength,
                maxLine: 1,
                autofocus: true,
                onTextChanged: (str) {
                  _text.value = str;
                  _isValid.value = _checkValid(str);
                },
              ),
            ),
            Container(
              width: double.infinity,
              margin: const EdgeInsets.only(top: 22),
              child: Obx(() {
                return MainButton(
                  text: '确定',
                  type: MainButtonType.primary,
                  enabled: _isValid.value,
                  onClick: () => onConfirm?.call(_text.value),
                );
              }),
            ),
          ],
        ),
      ),
    );
  }

  bool _checkValid(String? text) {
    return !text.isNullOrEmpty && (maxLength == null || text!.length <= maxLength!);
  }
}
